package com.moon.interface_api.aop;

import com.moon.interface_api.enums.ResultEnum;
import com.moon.interface_api.response.Result;
import com.moon.interface_api.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/*@Aspect
@Component*/
public class LoginAop {
    private Logger logger = LoggerFactory.getLogger(LogAop.class);
    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(public * com.moon.interface_api.controller.*.*(..))")
    public void request() {
    }
    
    

    @Around(value = "request()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        
        
        
        Object result = null;
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //登录，注册，发送验证码不用拦截
        if(!request.getRequestURL().toString().endsWith("/user/sendCode") &&
                !request.getRequestURL().toString().endsWith("/user/login")){
            logger.info("#############token校验#############");
            String token = request.getHeader("token");
            String phoneNum = null;
            try {
                phoneNum = TokenUtils.getUserInfo(token).split(",")[0];
            }catch (Exception e){
                return Result.error(ResultEnum.TOKEN_INVALID.getCode(),ResultEnum.TOKEN_INVALID.getMsg());
            }

            String check_token =(String) redisTemplate.opsForValue().get("token_" + phoneNum);
            if(StringUtils.isEmpty(check_token)){
                return Result.error(ResultEnum.TOKEN_INVALID.getCode(),ResultEnum.TOKEN_INVALID.getMsg());
            }
            if(!check_token.equals(token)){
                return Result.error(ResultEnum.TOKEN_INVALID.getCode(),ResultEnum.TOKEN_INVALID.getMsg());
            }
        }
        result = proceedingJoinPoint.proceed();
            
        return result;
    }
}
